"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const mobx_miniprogram_bindings_1 = require("mobx-miniprogram-bindings");
const index_1 = require("../../../store/index");
const dish_1 = require("../../../services/dish");
const appConfig_1 = require("../../../config/appConfig");
const toast_1 = require("../../../utils/toast");
Page({
    data: {
        loading: true,
        categoryList: [],
        activeCategory: "all",
        menuList: [],
        filteredList: [],
        summaryInfo: {
            totalItems: 0,
            totalStock: 0,
            funAvg: 0,
        },
        highlights: [],
        showCreatePanel: false,
        createForm: {
            name: "",
            categoryKey: "",
            description: "",
            coverUrl: "",
            stock: 0,
            funValue: 0,
            isActive: true,
        },
        createCategoryIndex: 0,
        uploadingCover: false,
        creating: false,
        showEditPanel: false,
        editingId: "",
        editingName: "",
        editStock: 0,
        editFunValue: 0,
        saving: false,
    },
    storeBindings: null,
    onLoad() {
        this.storeBindings = (0, mobx_miniprogram_bindings_1.createStoreBindings)(this, {
            store: index_1.globalStore,
            fields: ["menu"],
            actions: ["setMenu", "updateMenuSnapshot"],
        });
    },
    onUnload() {
        var _a, _b;
        (_b = (_a = this.storeBindings) === null || _a === void 0 ? void 0 : _a.destroyStoreBindings) === null || _b === void 0 ? void 0 : _b.call(_a);
    },
    onShow() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.loadMenu();
        });
    },
    loadMenu() {
        return __awaiter(this, void 0, void 0, function* () {
            this.setData({ loading: true });
            try {
                const res = yield (0, dish_1.fetchMenu)();
                index_1.globalStore.setMenu(res.menu);
                this.setupCategories(res.menu);
                this.updateSummary(res.menu);
                this.applyFilter(this.data.activeCategory, res.menu);
            }
            catch (error) {
                console.error("加载菜单失败", error);
                wx.showToast({ title: "加载失败", icon: "none" });
            }
            finally {
                this.setData({ loading: false });
            }
        });
    },
    getCategoryOptions() {
        if (this.data.categoryList.length) {
            return this.data.categoryList;
        }
        const set = new Map();
        (index_1.globalStore.categories || []).forEach((category) => {
            if (!set.has(category.key)) {
                set.set(category.key, {
                    key: category.key,
                    name: category.name,
                    icon: category.icon,
                });
            }
        });
        (index_1.globalStore.menu || []).forEach((item) => {
            if (!set.has(item.categoryKey)) {
                set.set(item.categoryKey, this.decorateCategory(item.categoryKey));
            }
        });
        return Array.from(set.values());
    },
    setupCategories(menu) {
        const set = new Map();
        (index_1.globalStore.categories || []).forEach((category) => {
            if (!set.has(category.key)) {
                set.set(category.key, {
                    key: category.key,
                    name: category.name,
                    icon: category.icon,
                });
            }
        });
        menu.forEach((item) => {
            if (!set.has(item.categoryKey)) {
                set.set(item.categoryKey, this.decorateCategory(item.categoryKey));
            }
        });
        const categoryList = Array.from(set.values());
        this.setData({ categoryList });
    },
    decorateCategory(key) {
        const matched = (index_1.globalStore.categories || []).find((item) => item.key === key);
        if (matched) {
            return { key, name: matched.name, icon: matched.icon };
        }
        const presets = {
            stirfry: { key, name: "热炒", icon: "🍲" },
            rice: { key, name: "主食", icon: "🍚" },
            fruit: { key, name: "鲜果", icon: "🍉" },
            snack: { key, name: "小食", icon: "🍡" },
            whole: { key, name: "粗粮", icon: "🥖" },
            dessert: { key, name: "甜品", icon: "🍰" },
            drink: { key, name: "饮品", icon: "🧃" },
        };
        const preset = presets[key];
        if (preset)
            return preset;
        return {
            key,
            name: key,
            icon: "🥗",
        };
    },
    updateSummary(menu) {
        const totalItems = menu.length;
        const totalStock = menu.reduce((sum, item) => sum + (item.stock || 0), 0);
        const funTotal = menu.reduce((sum, item) => sum + (item.funValue || 0), 0);
        const funAvg = totalItems ? Math.round((funTotal / totalItems) * 10) / 10 : 0;
        const highlights = [...menu].sort((a, b) => b.funValue - a.funValue).slice(0, 3);
        this.setData({
            summaryInfo: {
                totalItems,
                totalStock,
                funAvg,
            },
            highlights,
        });
    },
    applyFilter(categoryKey, menuList) {
        const source = menuList !== null && menuList !== void 0 ? menuList : this.data.menuList;
        const filtered = categoryKey === "all"
            ? source
            : source.filter((item) => item.categoryKey === categoryKey);
        this.setData({ menuList: source, filteredList: filtered, activeCategory: categoryKey });
    },
    handleCategoryTap(event) {
        const { key } = event.currentTarget.dataset;
        this.applyFilter(key);
    },
    handleOpenCreate() {
        var _a;
        const categoryList = this.getCategoryOptions();
        if (!categoryList.length) {
            wx.showModal({
                title: "暂无分类",
                content: "请先在后台配置菜品分类后再试。",
                showCancel: false,
            });
            return;
        }
        const fallbackCategory = ((_a = categoryList[0]) === null || _a === void 0 ? void 0 : _a.key) || "";
        if (!fallbackCategory) {
            wx.showToast({ title: "请先同步分类", icon: "none" });
            return;
        }
        const defaultIndex = Math.max(0, categoryList.findIndex((item) => item.key === fallbackCategory));
        const defaultForm = {
            name: "",
            categoryKey: fallbackCategory,
            description: "",
            coverUrl: "",
            stock: 0,
            funValue: 0,
            isActive: true,
        };
        this.setData({
            categoryList,
            showCreatePanel: true,
            createForm: defaultForm,
            createCategoryIndex: defaultIndex,
        });
    },
    handleCloseCreate() {
        this.setData({ showCreatePanel: false });
    },
    handleCreateInput(event) {
        const { field } = event.currentTarget.dataset;
        if (!field)
            return;
        const value = event.detail.value;
        if (field === "stock" || field === "funValue") {
            const num = Math.max(0, Number(value || 0));
            this.setData({ [`createForm.${field}`]: num });
            return;
        }
        this.setData({ [`createForm.${field}`]: value });
    },
    handleCreateStep(event) {
        const { field, delta } = event.currentTarget.dataset;
        if (!field)
            return;
        const current = this.data.createForm[field] || 0;
        const step = delta === "dec" ? -1 : 1;
        const next = Math.max(0, current + step);
        this.setData({ [`createForm.${field}`]: next });
    },
    handleCreateCategoryChange(event) {
        var _a;
        const index = Number((_a = event.detail.value) !== null && _a !== void 0 ? _a : 0);
        const category = this.data.categoryList[index];
        if (!category)
            return;
        this.setData({
            createCategoryIndex: index,
            "createForm.categoryKey": category.key,
        });
    },
    handleCreateToggleStatus(event) {
        const value = !!event.detail.value;
        this.setData({ "createForm.isActive": value });
    },
    handlePickCover() {
        if (this.data.uploadingCover)
            return;
        wx.chooseImage({
            count: 1,
            sizeType: ["compressed"],
            sourceType: ["album", "camera"],
            success: (res) => __awaiter(this, void 0, void 0, function* () {
                var _a, _b;
                const filePath = (_a = res.tempFilePaths) === null || _a === void 0 ? void 0 : _a[0];
                if (!filePath)
                    return;
                let coverUrl = filePath;
                if (appConfig_1.appConfig.useCloud && typeof ((_b = wx.cloud) === null || _b === void 0 ? void 0 : _b.uploadFile) === "function") {
                    const ext = filePath.split(".").pop() || "jpg";
                    const cloudPath = `menu/${Date.now()}_${Math.random()
                        .toString(16)
                        .slice(2)}.${ext}`;
                    this.setData({ uploadingCover: true });
                    try {
                        const uploadRes = yield wx.cloud.uploadFile({
                            cloudPath,
                            filePath,
                        });
                        coverUrl = uploadRes.fileID;
                    }
                    catch (error) {
                        console.error("upload cover failed", error);
                        wx.showToast({ title: "上传失败", icon: "none" });
                        this.setData({ uploadingCover: false });
                        return;
                    }
                    this.setData({ uploadingCover: false });
                }
                this.setData({ "createForm.coverUrl": coverUrl });
                (0, toast_1.toast)("已选择封面");
            }),
            fail: (err) => {
                var _a;
                if ((_a = err === null || err === void 0 ? void 0 : err.errMsg) === null || _a === void 0 ? void 0 : _a.includes("cancel"))
                    return;
                console.error("choose image failed", err);
                wx.showToast({ title: "无法选择图片", icon: "none" });
            },
        });
    },
    validateCreateForm(form) {
        if (!form.name || !form.name.trim()) {
            wx.showToast({ title: "请填写菜品名称", icon: "none" });
            return false;
        }
        if (!form.categoryKey) {
            wx.showToast({ title: "请选择分类", icon: "none" });
            return false;
        }
        if (!form.coverUrl) {
            wx.showToast({ title: "请上传图片", icon: "none" });
            return false;
        }
        return true;
    },
    handleCreateSubmit() {
        return __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c;
            if (this.data.creating)
                return;
            const form = this.data.createForm;
            const payload = Object.assign(Object.assign({}, form), { name: ((_a = form.name) === null || _a === void 0 ? void 0 : _a.trim()) || "", description: ((_b = form.description) === null || _b === void 0 ? void 0 : _b.trim()) || "", stock: Math.max(0, Number(form.stock || 0)), funValue: Math.max(0, Number(form.funValue || 0)), isActive: (_c = form.isActive) !== null && _c !== void 0 ? _c : true });
            if (!this.validateCreateForm(payload))
                return;
            this.setData({ creating: true });
            try {
                const res = yield (0, dish_1.createMenu)(payload);
                index_1.globalStore.updateMenuSnapshot(res.menu);
                (0, toast_1.toast)("菜品已创建");
                this.setData({ showCreatePanel: false });
                this.setupCategories(index_1.globalStore.menu);
                this.updateSummary(index_1.globalStore.menu);
                this.applyFilter(this.data.activeCategory, index_1.globalStore.menu);
            }
            catch (error) {
                console.error("create menu failed", error);
                wx.showToast({ title: "创建失败", icon: "none" });
            }
            finally {
                this.setData({ creating: false });
            }
        });
    },
    handleOpenEdit(event) {
        const { id } = event.currentTarget.dataset;
        const target = this.data.menuList.find((item) => item._id === id);
        if (!target)
            return;
        this.setData({
            showEditPanel: true,
            editingId: target._id,
            editingName: target.name,
            editStock: target.stock,
            editFunValue: target.funValue,
        });
    },
    handleCloseEdit() {
        this.setData({ showEditPanel: false, editingId: "" });
    },
    handleStep(event) {
        const { type } = event.currentTarget.dataset;
        const delta = event.currentTarget.dataset.delta === "dec" ? -1 : 1;
        if (type === "stock") {
            const value = Math.max(0, this.data.editStock + delta);
            this.setData({ editStock: value });
        }
        else {
            const value = Math.max(0, this.data.editFunValue + delta);
            this.setData({ editFunValue: value });
        }
    },
    handleStockInput(event) {
        const value = Math.max(0, Number(event.detail.value || 0));
        this.setData({ editStock: value });
    },
    handleFunInput(event) {
        const value = Math.max(0, Number(event.detail.value || 0));
        this.setData({ editFunValue: value });
    },
    handleSaveEdit() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.data.editingId || this.data.saving)
                return;
            this.setData({ saving: true });
            try {
                const res = yield (0, dish_1.updateMenu)({
                    _id: this.data.editingId,
                    stock: this.data.editStock,
                    funValue: this.data.editFunValue,
                });
                index_1.globalStore.updateMenuSnapshot(res.menu);
                (0, toast_1.toast)("已更新库存");
                this.handleCloseEdit();
                this.applyFilter(this.data.activeCategory, index_1.globalStore.menu);
            }
            catch (error) {
                console.error("更新库存失败", error);
                (0, toast_1.toast)(error.message || "保存失败");
            }
            finally {
                this.setData({ saving: false });
            }
        });
    },
    handleDeleteDish(event) {
        const { id, name } = event.currentTarget.dataset;
        if (!id)
            return;
        wx.showModal({
            title: "删除菜品",
            content: `确定删除「${name || "该菜品"}」吗？`,
            confirmText: "删除",
            confirmColor: "#d64561",
            success: (res) => __awaiter(this, void 0, void 0, function* () {
                if (!res.confirm)
                    return;
                try {
                    yield (0, dish_1.removeMenu)(id);
                    index_1.globalStore.removeMenuSnapshot(id);
                    (0, toast_1.toast)("已删除");
                    this.setupCategories(index_1.globalStore.menu);
                    this.updateSummary(index_1.globalStore.menu);
                    this.applyFilter(this.data.activeCategory, index_1.globalStore.menu);
                }
                catch (error) {
                    console.error("delete menu failed", error);
                    wx.showToast({ title: "删除失败", icon: "none" });
                }
            }),
        });
    },
});
